<?php
/**
 * 订单支付
 */
namespace app\api\controller\pay;
use app\api\controller\Common;
use app\api\model\Paymodel;
use app\api\controller\pay\Alipay;
use app\api\model\user\Ordermodel;
use think\facade\Config;
class Payment extends Common{
    protected $data;
    public function initialize()
    {
        parent::initialize();
        $this->data = $this->request->except(['sign','accessKey','token']);
    }

    /* ------------------------------------------------------ 微信支付 ------------------------------------------------- */
    /**
     * 微信支付订单 - APP调用
     * @param order_id 订单ID
     * @param order_type 订单类型：1-现货出价订单、2求购订单、3-立即购买订单
     * @return string
     */
    public function wxPay(){
        $this->checkUserLogin(); // 验证登录
        $data = $this->data;
        $order_id = $data['order_id'];
        if (empty($order_id)) {
            $this->showError('没有要支付的订单', 'GET_ERROR');
        }
        $model = new Paymodel();
        switch($data['order_type']){
            case 1:
                $order_info = $model->getSpotOrderInfo($order_id);
                $total_fee = intval($order_info['buy_deposit'] * 100); 
                $body = 'VVME-支付现货出价保证金';
                break;
            case 2:
                $order_info = $model->getSpotOrderInfo($order_id);
                $total_fee = intval($order_info['buy_deposit'] * 100); 
                $body = 'VVME-支付求购定金';
                break;
            case 3:
                $order_info = $model->getSpotOrderInfo($order_id);
                $total_fee = intval($order_info['buy_deposit'] * 100); 
                $body = 'VVME-支付立即变现保证金';
                break;
            case 4:
                $order_info = $model->getOrderInfo($order_id);
                $total_fee = intval($order_info['order_price'] * 100); 
                $body = 'VVME-支付求购货款';
                break;
            case 5:
                $order_info = $model->getOrderInfo($order_id);
                $total_fee = intval($order_info['order_price'] * 100); 
                $body = 'VVME-支付立即购买货款';
                break;
        }
        if(false == $order_info){ // 验证该订单是否支付
            $this->showError('支付的订单不存在', 'GET_ERROR');
        }
        $wxPay = new Wxpay();
        $out_trade_no = $order_id . rand(1000,9999);
        $notify_url = Config::get('app.wxpay.notify_url');
        $res = $wxPay->getPrePayOrder($body, $out_trade_no, $total_fee, $notify_url); 
        if($res->return_code != 'SUCCESS'){
            $this->showError($res->return_msg, $res->return_code);
        }

        //记录日志
		db('order_pay_log')->insert([
			'user_id'=>$this->user['id'],
			'openid'=>'',
			'order_id'=>$order_info['id'],
			'out_trade_no'=>$out_trade_no,
			'total_fee'=>$total_fee,
			'body'=>$body,
            // 'attach'=>$attach,
            'order_type'=>$data['order_type'],
            'pay_type'=>1,
			'operate'=>'wx.unifiedorder',
			'create_time'=>toDate(time()),
        ]);
        
        return $this->showSuccess('下单成功', $res);
    }

    /**
     * 微信支付回调
     *
     * @return void
     */
    public function wxNotify()
    {
        $wxPay = new Wxpay();
        $postObj = $wxPay->payCallback();
        if($postObj === false){
            return false;
        }

        //处理实际业务
        $out_trade_no = $postObj->out_trade_no; 
        $payLog = db('order_pay_log')->where(['out_trade_no'=>$out_trade_no])->find(); 
        if(empty($payLog)){
            trace('无效订单：out_trade_no='.$out_trade_no,'wxNotify');
            return false;
        }
        elseif($payLog['status'] == 1){
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';   //不写一直回调
            exit;
        }
        else{
            //修改订单状态
            $this->afterPayNotify($payLog);

            //记录支付日志
            db('order_pay_log')->where(['id'=>$payLog['id']])->update([
                'transaction_id' => $postObj->transaction_id,
                'status' => 1,
                'pay_time_end' => $postObj->time_end,
            ]);

            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>';   //不写一直回调
            exit;
        }
        
    }

    /**
     * 微信支付退款通知回调
     *
     * @return void
     */
    public function wxRefundNotify()
    {
        $wxPay = new Wxpay();
        $postObj = $wxPay->refundCallback();
        if($postObj === false){
            return false;
        }

        //处理实际业务
        $out_refund_no = $postObj->out_refund_no; 
		$payLog = db('order_pay_log')->where(['out_refund_no'=>$out_refund_no])->find(); 
        if(empty($payLog)){
            trace('无效订单：out_trade_no='.$out_refund_no,'wxNotify');
            $return_code = 'FAIL';
        }
        elseif($payLog['refund_status'] == 'SUCCESS'){
            $return_code = 'SUCCESS';
        }
        else{
            //修改订单状态
            if($payLog['order_type'] == 1 || $payLog['order_type'] == 2){
                db('spot_order_info')->where(['id'=>$payLog['order_id']])->update([
                    'refund_status' => 1,
                    'refund_time_end' => date('Y-m-d H:i:s')
                ]);
            }
            elseif($payLog['order_type'] == 3){
                db('order_info')->where(['id'=>$payLog['order_id']])->update([
                    'refund_status' => 1,
                    'refund_time_end' => date('Y-m-d H:i:s')
                ]);
            }

            //记录支付日志
            db('order_pay_log')->where(['id'=>$payLog['id']])->update([
                'refund_id' => $postObj->refund_id,
                'refund_status' => $postObj->refund_status,
                'refund_time_end' => $postObj->success_time,
            ]);

        }

        $returnArray = [];
        $returnArray['return_code'] = $return_code;
        $returnArray['return_msg'] = 'OK';
        $retXml = $wxPay->arrayToXml($returnArray);
        echo $retXml; //不写一直回调
        exit;
    }

    /* ------------------------------------------------------ 阿里支付宝 支付 ------------------------------------------------- */
    /**
     * 支付宝支付订单 - APP调用
     * @param order_id 订单ID
     * @param order_type 订单类型：1-现货出价订单、2求购订单、3-立即购买订单
     * @return string
     */
    public function aliPay(){
        $this->checkUserLogin(); // 验证登录
        $data = $this->data;
        $out_trade_no = $data['order_id'];
        if (empty($out_trade_no)) {
            $this->showError('没有要支付的订单', 'GET_ERROR');
        }
        $model = new Paymodel();
        switch($data['order_type']){
            case 1:
                $order_info = $model->getSpotOrderInfo($out_trade_no);
                $total_amount = $order_info['buy_deposit']; 
                $subject = 'VVME-现货出价保证金';
                break;
            case 2:
                $order_info = $model->getSpotOrderInfo($out_trade_no);
                $total_amount = $order_info['buy_deposit']; 
                $subject = 'VVME-求购定金';
                break;
            case 3:
                $order_info = $model->getSpotOrderInfo($out_trade_no);
                $total_amount = $order_info['buy_deposit']; 
                $subject = 'VVME-立即变现保证金';
                break;
            case 4:
                $order_info = $model->getOrderInfo($out_trade_no);
                $total_amount = $order_info['order_price']; 
                $subject = 'VVME-支付求购货款';
                break;
            case 5:
                $order_info = $model->getOrderInfo($out_trade_no);
                $total_amount = $order_info['order_price']; 
                $subject = 'VVME-支付立即购买货款';
                break;
        }
        if(false == $order_info){ // 验证该订单是否支付
            $this->showError('支付的订单不存在', 'GET_ERROR');
        }
        $pay = new Alipay();
        $body = '商品['.$order_info['gid'].']: '.$order_info['sku_name'];
        $res = $pay->createAppPay($out_trade_no,$body, $subject, $total_amount); // TODO 待申请支付账号
 
        if(false === $res){
            $this->showError('微信预下单失败，请重试', 'GET_ERROR');
        }

        //记录日志
		db('order_pay_log')->insert([
			'user_id'=>$this->user['id'],
			'openid'=>'',
			'order_id'=>$order_info['id'],
			'out_trade_no'=>$out_trade_no,
			'total_fee'=>$total_amount * 100,
			'body'=>$subject,
            // 'attach'=>$attach,
            'order_type'=>$data['order_type'],
            'pay_type'=>2,
			'operate'=>'alipay.trade.app.pay',
			'create_time'=>toDate(time()),
		]);
        
        return $this->showSuccess('支付成功', $res);
    }

    /**
     * 支付宝支付回调
     *
     * @return void
     */
    public function aliNotify()
    {
        $aliPay = new Alipay();
        $request = $aliPay->payCallback();

        if($request === false){
            echo "fail";
            exit;
        }

        //处理实际业务
        $out_trade_no = $request['out_trade_no'];
        $payLog = db('order_pay_log')->where(['out_trade_no'=>$out_trade_no])->find(); 
        if(empty($payLog)){
            trace('无效订单：out_trade_no='.$out_trade_no,'aliNotify');
            return false;
        }
        elseif($payLog['status'] == 1){
            echo "success";   //不写一直回调
            exit;
        }
        else{
            //修改订单状态
            $this->afterPayNotify($payLog);

            //记录支付日志
            db('order_pay_log')->where(['id'=>$payLog['id']])->update([
                'transaction_id' => $request['trade_no'],
                'status' => 1,
                'pay_time_end' => $request['gmt_payment'],
            ]);

            echo "success"; // 请不要修改或删除，不写一直回调
            exit;
        }
    }

    public function afterPayNotify($payLog)
    {
        if($payLog['order_type'] == 1 || $payLog['order_type'] == 2){
            db('spot_order_info')->where(['id'=>$payLog['order_id']])->update([
                'order_status' => 2,
                'pay_method' => 1,
                'pay_status' => 1,
                'pay_time' => date('Y-m-d H:i:s')
            ]);
        }
        elseif($payLog['order_type'] == 3){ //立即变现支付保证金
            db('spot_order_info')->where(['id'=>$payLog['order_id']])->update([
                'order_status' => 2,
                'pay_method' => 1,
                'pay_status' => 1,
                'pay_time' => date('Y-m-d H:i:s')
            ]);
            //求购订单, 状态：41-待支付货款
            $sport_order = db('spot_order_info')->where(['id'=>$payLog['order_id']])->find();
            $pur_sport_order = db('spot_order_info')->where(['id'=>$sport_order['purchase_order_id']])->find(); 
            db('spot_order_info')->where(['id'=>$pur_sport_order['id']])->update([
                'order_status' => 41
            ]);
        }
        elseif($payLog['order_type'] == 4){//求购：支付尾款
            $order = db('order_info')->where(['id'=>$payLog['order_id']])->find();
            db('order_info')->where(['id'=>$payLog['order_id']])->update([
                'order_status' => 2,
                'pay_method' => 1,
                'pay_status' => 1,
                'pay_time' => date('Y-m-d H:i:s')
            ]);
            //供货订单
            db('spot_order_info')->where(['id'=>$order['spot_order_id']])->update([
                'order_status' => 42,
            ]);
            //求购订单
            db('spot_order_info')->where(['id'=>$order['purchase_order_id']])->update([
                'order_status' => 42,
            ]);
        }
        elseif($payLog['order_type'] == 5){//立即购买：支付货款
            $order = db('order_info')->where(['id'=>$payLog['order_id']])->find();
            db('order_info')->where(['id'=>$payLog['order_id']])->update([
                'order_status' => 2,
                'pay_method' => 1,
                'pay_status' => 1,
                'pay_time' => date('Y-m-d H:i:s')
            ]);
            db('spot_order_info')->where(['id'=>$order['spot_order_id']])->update([
                'order_status' => 42,
            ]);
        }
    }



}